var netWork = require('../../utils/netWork.js');
var apiCode = require('../../utils/openApiCode.js');
var api = require('../../utils/api.js');
const util = require('../../utils/util');
const log = require('../../utils/logs.js');
const QR = require('../../utils/weapp-qrcode.js')
var Base64 = require('../../utils/base64.js');
var bobing = require('../../utils/bobing.js');
var model = require('../../model/model.js')
import {
    isShowReminderOfExpired,
    pickInfo
} from "../../utils/publicMethods";
import {requestSubscribeMessage} from "../../utils/wxapi";
const app = getApp();
var _lower = true;
var isClick = true;
// var pageNum = 1;
//选择城市
var show = false;
var addressInfo = {};
var item = {};
var isClickReceivePrizes = true;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imagesUrl: getApp().globalData.imagesUrl,
        prizeList: [], //中奖记录
        ticketList: {}, //可用礼券记录
        wlList: {}, //物流记录
        topHeight: 0,
        showFlag: -1,
        wlInfo: "",
        pageNum: 0,
        pageNumNew: 1,
        pageNumTticket: 1,
        hidden: true,
        isShowWL: false, //显示物流
        isShowModalRule: false, //是否显示活动规则
        ani: 0, //动画是否执行
        triggered: false, //设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
        triggeredTicket: false, //设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
        tabFlag: 'prizeList',
        isShowQRcode: false, //展示核销二维码
        isSubMsg: false, //引导订阅
        height: 527,
        zindex: 1, //当有记录时，记录在红包上边。当没有记录时红包在上边
        materialInfo: {}, //邮寄信息
        address: '请选择地区', //地区文字显示
        item: { //城市选择器信息
            show: show
        },
        addressMsg: '', //详细地址
        formValue: {}, //form表单邮寄信息
        isShowEntityPopup: false, //是否显示实物弹窗
        entityData: {}, //实物弹窗奖励信息
        isShowEntityTips: false, //实物领取成功提示
        entityIndex: 0, //实物下标
        entityPrizeOrderId: "", //实物奖励订单id
        entityPrizeId: "", //实物奖励id
        redEnvelopes: 0, //红包
        currentType: 1, //先前选择的类型 1 券/奖 tab =2 红包 tab=3 积分
        menu_bg_left: '/prizeRecord/menu_left.png',
        menu_bg_center: '/prizeRecord/menu_center.png',
        menu_bg_right: '/prizeRecord/menu_right.png',
        couponScrollViewHeight: 200, //卷、实物ScrollView高度
        commonHeight: 200, //红包、积分ScrollView高度
        integral: 0, //积分
        redEnvelopNum: 0, //红包
        tanban_big_bg: getApp().globalData.imagesUrl + '/jingdianPage/tanban_big_bg1.png',
        back: true,
        home: false,
        showFootball: false, //显示世界杯竞猜弹窗
        footballPrizeOrderId: "", //竞猜奖励ID
        currentTypeTabIndex: 1 //当前选中的typeTab
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
        this.setData({
            topHeight: topHeight,

            goToganguo: wx.getStorageSync('goToganguo')
        });
        console.log('gotoGG:' + wx.getStorageSync('goToganguo'))
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        try {
            const {
                SDKVersion = ''
            } = wx.getSystemInfoSync();
            console.log('SDKVersion' + SDKVersion)
            const compatibility = util.compareVersion(SDKVersion, '2.2.2');
            console.log('compatibility' + compatibility)
            if (compatibility == -1) {
                wx.showModal({
                    content: '您的微信版本过低，请升级后再来吧~',
                    confirmText: '我知道了',
                    showCancel: false
                });
                return;
            }
        } catch (e) {}
        try {
            // 检测是否可以调用getUpdateManager检查更新
            if (!wx.canIUse("getUpdateManager")) return;
            let updateManager = wx.getUpdateManager();
            // 获取全局唯一的版本更新管理器，用于管理小程序更新
            updateManager.onCheckForUpdate(function (res) {
                console.log(res)
                // 监听向微信后台请求检查更新结果事件
                console.log("是否有新版本：" + res.hasUpdate);
                if (res.hasUpdate) {
                    //如果有新版本
                    // 小程序有新版本，会主动触发下载操作
                    updateManager.onUpdateReady(function () {
                        //当新版本下载完成，会进行回调
                        wx.showModal({
                            title: '更新提示',
                            content: '新版本已经准备好，单击确定重启小程序',
                            showCancel: false,
                            success: function (res) {
                                if (res.confirm) {
                                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                                    updateManager.applyUpdate();
                                }
                            }
                        })
                    })
                    // 小程序有新版本，会主动触发下载操作（无需开发者触发）
                    updateManager.onUpdateFailed(function () {
                        //当新版本下载失败，会进行回调
                        wx.showModal({
                            title: '提示',
                            content: '检查到有新版本，但下载失败，请稍后尝试',
                            showCancel: false,
                        })
                    })
                }
            });
        } catch (e) {
            e
        }
        log.info('options==' + JSON.stringify(options))
        var that = this;
        that.setData({
            icon: wx.getStorageSync('productType') == 4 ? 'xinyouranPage/loading_logo' : 'common/loading',
        })
        // 链接带过来的二维码
        if (options.q) {
            var str = decodeURIComponent(options.q);
            var index = str.lastIndexOf("\/");
            str = str.substring(index + 1, str.length);
            wx.setStorageSync('qrCode', str);
        }
        /**
         * 判断链接带过来的二维码和session中二维码是否有值
         */
        //userid
        if (options.userId) {
            wx.setStorageSync('userId', options.userId);
            if (wx.getStorageSync('sendType')) {
                options.type = wx.getStorageSync('sendType');
                options.prizeOrderId = wx.getStorageSync('sendPrizeOrderId');
                wx.removeStorageSync('sendPrizeOrderId');
                wx.removeStorageSync('sendType');
            }
        }
        // 用户类型
        if (options.userType) {
            wx.setStorageSync('userType', options.userType);
        }

        // 判断是否有userId，跳转h5进行授权
        if (wx.getStorageSync('userId') == '' || wx.getStorageSync('userId') == null || wx.getStorageSync('userId') == undefined) {
            if (options.type == "sendEntity") {
                wx.setStorageSync('sendPrizeOrderId', options.prizeOrderId);
                wx.setStorageSync('sendType', options.type);
            }
            wx.redirectTo({
                url: '../webview/webview?intoType=prizeRecord',
            })
        } else {

            //查询
            this.queryPrizeRecord();
            // this.getOpendCount();
        }
        let m = wx.getStorageSync('materialInfo');
        if (m) {
            this.setData({
                materialInfo: m,
                address: m.receiveProvinceName + ' ' + m.receiveCityName + ' ' + m.receiveDistrictName,
                color: true,
                addressMsg: m.receiveAddress
            })
            addressInfo = this.data.materialInfo;
        } else {
            let userPhone = wx.getStorageSync('userPhone');
            let m1 = {};
            if (userPhone != "" && userPhone != null && userPhone != undefined) {
                m1['receivePhone'] = userPhone;
            }
            this.setData({
                materialInfo: m1
            })
        }
        if (options.type == "sendEntity") {
            this.setData({
                back: false,
                home: true,
                sendType: options.type
            })
            this.openEntityPopup(options.prizeOrderId);
        }
    },

    /**
     * 查询中奖记录
     */
    async queryPrizeRecord() {

        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        this.isLoading(true, "正在查询...")

        const that = this;
        console.log("查询订单");
        //先查询新的订单表
        let prizeList = await this.queryNewPrizeList();
        if (prizeList != null && prizeList != "") {
            that.setData({
                prizeList: prizeList,
                // showFlag: prizeList.length,
                zindex: prizeList.length == 0 ? 0 : 9999
            });
            if (prizeList.length >= 10) {
                // that.setData({
                //   prizeList: prizeList,
                //   showFlag: prizeList.length,
                //   zindex: prizeList.length == 0 ? 0 : 9999
                // });
                // if (that.data.pageNumNew != 1) {
                // }
                return;
            }

        }

        // log.info("[queryPrizeRecord]--->[pageNum]" + that.data.pageNum+'--->[userid]'+wx.getStorageSync('userId'));
        //中奖记录查询
        // netWork.POST('getUserPrizeListByTab', {
        //   data: {
        //     userId: wx.getStorageSync('userId'),
        //     pageNum: 1,
        //     tab:this.data.currentType
        //   },
        //   success: function (res) {
        //     setTimeout(function () {
        //       that.isLoading(false);
        //     }, 1000);
        //     if (res.data.retCode == undefined) {
        //       wx.redirectTo({
        //         url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        //       })
        //     }
        //     if (res.data.retCode == "0000") {
        //       if (res.data.data != null && res.data.data != "") {
        //         that.setData({
        //           pageNum: that.data.pageNum + 1
        //         });
        //         //构造新数组，把有积分的记录拆分成两条记录
        //         let prizeRecordArray = [];
        //         for (var index in res.data.data) {
        //             if(that.data.currentType == 3){
        //                 if (res.data.data[index].prizeType == '3') { //积分奖项特殊处理
        //                     let jf1 = new Object();
        //                     jf1 = JSON.parse(JSON.stringify(res.data.data[index])); //积分
        //                     jf1.prizeName = res.data.data[index].prizeIntegration + '积分';
        //                     prizeRecordArray.push(jf1);
        //                   } else if(res.data.data[index].point != null && res.data.data[index].point != 0) {
        //                     let jf = new Object();
        //                     jf = JSON.parse(JSON.stringify(res.data.data[index])); //积分
        //                     jf.prizeName = res.data.data[index].point + '积分';
        //                     prizeRecordArray.push(jf);
        //                   }
        //             }else{
        //                 prizeRecordArray.push(res.data.data[index]);
        //             }
        //         }
        //         if (prizeList != null && prizeList != "" && that.data.pageNumNew == 1) {
        //           prizeRecordArray = prizeList.concat(prizeRecordArray);
        //         }
        //         console.log(prizeRecordArray)
        //         that.setData({
        //           prizeList: prizeRecordArray,
        //           showFlag: prizeRecordArray.length,
        //           zindex: prizeRecordArray.length == 0 ? 0 : 9999
        //         });
        //       } else {
        //         if (prizeList != null && prizeList != "") {


        //         } else {

        //           that.setData({
        //             prizeList: "",
        //             showFlag: 0,
        //             zindex: 0
        //           });
        //         }
        //       }
        //     } else {
        //       wx.showToast({
        //         title: '查询失败，请稍后重试~',
        //         icon: 'none',
        //         duration: 2000
        //       })
        //     }

        //   },
        //   fail: function (err) {
        //     that.isLoading(false);
        //     //查询失败
        //     wx.showToast({
        //       title: '查询失败，请稍后重试~',
        //       icon: 'none',
        //       duration: 2000
        //     })

        //   }
        // });
    },
    queryNewPrizeList() {
        const that = this;
        return new Promise((resolve, reject) => {
            netWork.POST_Json('v3/getUserPrizeListByTab', {
                data: {
                    userId: wx.getStorageSync('userId'),
                    pageNum: that.data.pageNumNew,
                    tab: that.data.currentType,
                    typeTab: that.data.currentTypeTabIndex
                },
                success: function (res) {
                    that.isLoading(false);
                    if (res.data.retCode == undefined) {
                        resolve("");
                    }

                    setTimeout(function () {
                        that.setData({
                            hidden: true
                        });
                    }, 1000);
                    if (res.data.retCode == undefined) {
                        wx.redirectTo({
                            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                        })
                    }
                    if (res.data.retCode == '0000') {
                        if (res.data.data != null && res.data.data != "") {
                            //let list = that.data.prizeList;
                            let prizeRecordArray = [];
                            for (var index in res.data.data) {
                                res.data.data[index].status === 1 ? res.data.data[index].status = 2 : '';
                                if (that.data.currentType == 3) {
                                    if (res.data.data[index].prizeType == '3') { //积分奖项特殊处理
                                        let jf1 = new Object();
                                        jf1 = JSON.parse(JSON.stringify(res.data.data[index])); //积分
                                        jf1.prizeName = res.data.data[index].prizeIntegration + '积分';
                                        prizeRecordArray.push(jf1);
                                    } else if (res.data.data[index].point != null && res.data.data[index].point != 0) {
                                        let jf = new Object();
                                        jf = JSON.parse(JSON.stringify(res.data.data[index])); //积分
                                        jf.prizeName = res.data.data[index].point + '积分';
                                        prizeRecordArray.push(jf);
                                    }
                                } else {
                                    prizeRecordArray.push(res.data.data[index]);
                                }
                            }
                            resolve(prizeRecordArray);
                        } else {
                            resolve("");
                        }
                    } else {
                        resolve("");
                        //查询失败
                        wx.showToast({
                            title: '查询失败，请稍后重试~',
                            icon: 'none',
                            duration: 2000
                        })
                    }

                },
                fail: function (res) {
                    resolve("");
                }
            });
        });
    },
    /**
     * 查询可用礼券
     */
    queryTicketRecord() {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })

        const that = this;
        that.setData({
            hidden: false
        });
        // log.info("[queryPrizeRecord]--->[pageNum]" + that.data.pageNum+'--->[userid]'+wx.getStorageSync('userId'));
        //中奖记录查询
        netWork.POST('xhtx/little/QueryVIPTickets', {
            data: {
                userId: wx.getStorageSync('userId'),
                mobileNo: wx.getStorageSync('userPhone'),
                pageNum: that.data.pageNumTticket
            },
            success: function (res) {
                setTimeout(function () {
                    that.setData({
                        hidden: true
                    });
                }, 1000);
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }

                if (res.data.retCode == "0000") {
                    if (res.data.data != null && res.data.data != "") {
                        let ticketRecordArray = [];
                        for (var index in res.data.data) {
                            let ticket = new Object();
                            ticket = JSON.parse(JSON.stringify(res.data.data[index]));
                            console.info(ticket)
                            if (ticket.FTicketNo != "" && ticket.FTicketNo != null) {
                                ticket.qrcodeURL = that.drawImg(ticket.FTicketNo);
                                ticketRecordArray.push(ticket);

                            }

                        }
                        that.setData({
                            ticketList: ticketRecordArray,
                            showFlag: ticketRecordArray.length,
                            zindex: ticketRecordArray.length == 0 ? 0 : 9999,

                        });
                    } else {
                        that.setData({
                            ticketList: "",
                            showFlag: 0,
                            zindex: 0
                        });
                    }
                } else {
                    wx.showToast({
                        title: '查询失败，请稍后重试~',
                        icon: 'none',
                        duration: 2000
                    })
                }

            },
            fail: function (err) {
                that.setData({
                    hidden: true
                });
                //查询失败
                wx.showToast({
                    title: '查询失败，请稍后重试~',
                    icon: 'none',
                    duration: 2000
                })

            }
        });
    },
    /**
     * 下拉刷新可用礼券
     */
    onRefreshTicket() {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        const that = this;
        if (that._freshing) return
        that._freshing = true

        console.log("[onLoad-pageNumTticket]" + that.data.pageNumTticket);
        this.setData({
            pageNumTticket: 1,
            hidden: false
        })
        // log.info("[queryPrizeRecord]--->[pageNum]" + that.data.pageNum+'--->[userid]'+wx.getStorageSync('userId'));
        //中奖记录查询
        netWork.POST('xhtx/little/QueryVIPTickets', {
            data: {
                userId: wx.getStorageSync('userId'),
                mobileNo: wx.getStorageSync('userPhone'),
                pageNum: that.data.pageNumTticket
            },
            success: function (res) {
                setTimeout(function () {
                    that.setData({
                        hidden: true
                    });
                }, 1000);
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }

                if (res.data.retCode == "0000") {
                    setTimeout(function () {
                        that.setData({
                            triggeredTicket: false,

                        })
                        that._freshing = false;
                    }, 1000);
                    that.setData({
                        ticketList: {},
                        showFlag: 0,
                        zindex: 0
                    });
                    if (res.data.data != null && res.data.data != "") {
                        let ticketRecordArray = [];
                        for (var index in res.data.data) {
                            let ticket = new Object();
                            ticket = JSON.parse(JSON.stringify(res.data.data[index]));
                            console.info(ticket)
                            if (ticket.FTicketNo != "" && ticket.FTicketNo != null) {
                                ticket.qrcodeURL = that.drawImg(ticket.FTicketNo);
                                ticketRecordArray.push(ticket);

                            }

                        }
                        that.setData({
                            ticketList: ticketRecordArray,
                            showFlag: ticketRecordArray.length,
                            zindex: ticketRecordArray.length == 0 ? 0 : 9999,

                        });
                        api.cancelLoading();
                    } else {
                        that.setData({
                            ticketList: "",
                            showFlag: 0,
                            zindex: 0
                        });
                        api.cancelLoading();
                    }
                } else {
                    wx.showToast({
                        title: '查询失败，请稍后重试~',
                        icon: 'none',
                        duration: 2000
                    })
                }

            },
            fail: function (err) {
                that.setData({
                    hidden: true
                });
                //查询失败
                wx.showToast({
                    title: '查询失败，请稍后重试~',
                    icon: 'none',
                    duration: 2000
                })

            }
        });
    },


    // 加载更多
    async lower() {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        var that = this;
        console.log("[进入分页加载新订单]" + that.data.pageNumNew);
        console.log("[进入分页加载新订单]" + that._freshing);
        if (that._freshing) return
        that._freshing = true
        that.setData({
            pageNumNew: that.data.pageNumNew + 1,
            hidden: false
        })
        let list = that.data.prizeList;
        //先查询新的订单表
        let prizeList = await this.queryNewPrizeList();

        if (prizeList != null && prizeList != "") {

            that._freshing = false;
            that.setData({
                prizeList: list.concat(prizeList),
                showFlag: prizeList.length,
                zindex: prizeList.length == 0 ? 0 : 9999
            });
            return;
        }
        // else {
        //   that.setData({
        //     pageNumNew: that.data.pageNumNew - 1
        //   })

        // }
        // that.setData({
        //   pageNum: that.data.pageNum + 1
        // })
        // console.log("[进入分页加载老订单]" + that.data.pageNum);
        // console.log("[进入分页加载老订单]" + that._freshing);
        // netWork.POST('getUserPrizeListByTab', {
        //   data: {
        //     userId: wx.getStorageSync('userId'),
        //     pageNum: that.data.pageNum,
        //     tab:this.data.currentType
        //   },
        //   success: function (res) {
        //     that._freshing = false;
        //     setTimeout(function () {
        //       that.setData({
        //         hidden: true
        //       });
        //     }, 1000);
        //     if (res.data.retCode == undefined) {
        //       wx.redirectTo({
        //         url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        //       })
        //     }
        //     if (res.data.retCode == '0000') {
        //       if (res.data.data != null && res.data.data != "") {

        //         let prizeRecordArray = [];
        //         for (var index in res.data.data) {
        //             if(that.data.currentType == 3){
        //                 if (res.data.data[index].prizeType == '3') { //积分奖项特殊处理
        //                     let jf1 = new Object();
        //                     jf1 = JSON.parse(JSON.stringify(res.data.data[index])); //积分
        //                     jf1.prizeName = res.data.data[index].prizeIntegration + '积分';
        //                     prizeRecordArray.push(jf1);
        //                 } else if(res.data.data[index].point != null && res.data.data[index].point != 0) {
        //                     let jf = new Object();
        //                     jf = JSON.parse(JSON.stringify(res.data.data[index])); //积分
        //                     jf.prizeName = res.data.data[index].point + '积分';
        //                     prizeRecordArray.push(jf);
        //                 }
        //             }else{
        //                 prizeRecordArray.push(res.data.data[index]);
        //             }
        //         }
        //         that.setData({
        //           prizeList: list.concat(prizeRecordArray),
        //         })
        //       } else {
        //         that.setData({
        //           pageNum: that.data.pageNum - 1

        //         })
        //       }
        //     } else {
        //       that.setData({
        //         pageNum: that.data.pageNum - 1
        //       })
        //       //查询失败
        //       wx.showToast({
        //         title: '查询失败，请稍后重试~',
        //         icon: 'none',
        //         duration: 2000
        //       })
        //     }
        //   },
        //   fail: function (err) {
        //     that._freshing = false;
        //     that.setData({
        //       pageNum: that.data.pageNum - 1,
        //       hidden: true

        //     })
        //     //查询失败
        //     wx.showToast({
        //       title: '查询失败，请稍后重试~',
        //       icon: 'none',
        //       duration: 2000
        //     })
        //   }
        // });
    },

    // 加载更多---礼券
    lowerTicket: function () {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        var that = this;
        that.setData({
            hidden: false
        });
        console.log("[进入分页加载]" + that._freshing);
        if (that._freshing) return
        that._freshing = true
        that.setData({
            pageNumTticket: that.data.pageNumTticket + 1
        })
        netWork.POST('xhtx/little/QueryVIPTickets', {
            data: {
                userId: wx.getStorageSync('userId'),
                mobileNo: wx.getStorageSync('userPhone'),
                pageNum: that.data.pageNumTticket
            },
            success: function (res) {
                setTimeout(function () {
                    that.setData({
                        hidden: true
                    });
                }, 1000);
                that._freshing = false;
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == '0000') {
                    if (res.data.data != null && res.data.data != "") {
                        let list = that.data.ticketList;
                        let ticketRecordArray = [];
                        for (var index in res.data.data) {
                            let ticket = new Object();
                            ticket = JSON.parse(JSON.stringify(res.data.data[index]));
                            console.info(ticket)
                            if (ticket.FTicketNo != "" && ticket.FTicketNo != null) {
                                ticket.qrcodeURL = that.drawImg(ticket.FTicketNo);
                                ticketRecordArray.push(ticket);

                            }

                        }
                        that.setData({
                            ticketList: list.concat(ticketRecordArray),
                        })
                    } else {
                        that.setData({
                            pageNumTticket: that.data.pageNumTticket - 1

                        })
                    }
                } else {
                    that.setData({
                        pageNumTticket: that.data.pageNumTticket - 1
                    })
                    //查询失败
                    wx.showToast({
                        title: '查询失败，请稍后重试~',
                        icon: 'none',
                        duration: 2000
                    })
                }
            },
            fail: function (err) {
                that._freshing = false;
                that.setData({
                    pageNumTticket: that.data.pageNumTticket - 1,
                    hidden: true

                })
                //查询失败
                wx.showToast({
                    title: '查询失败，请稍后重试~',
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },

    /**
     * 显示活动规则
     */
    showRule: function () {
        wx.navigateTo({
            url: '../ruleh5/ruleh5'
        })
    },

    /**
     * 关闭活动规则
     */
    clickClose: function () {

        this.setData({
            ani: 1,
            wlInfo: "",
            wlList: {}
        })
        const that = this;

        setTimeout(function () {
            that.setData({
                isShowModalRule: false,
                isShowModal: false,
                height: 0
            })
        }, 180);
    },
    // /**
    //  * 实物奖领奖
    //  */
    // swprizeDraw: function (event) {
    //   api.judgeNetworkStatus(function (res) {
    //     if ("none" == res) return;
    //   })
    //   let prizeInfo = event.currentTarget.dataset.prizeinfo;
    //   if (prizeInfo == undefined || prizeInfo == null || prizeInfo == "") {
    //     return;
    //   }
    //   // let materialInfo = prizeInfo.materialInfo;
    //   // if (prizeInfo.encouragePrizeList == null) { //非多选一
    //   //   wx.redirectTo({
    //   //     url: '../receiptInfo/receiptInfo?source=2&prizeOrderId=' + prizeInfo.prizeOrderId + "&prizeId=" + prizeInfo.prizeId,
    //   //   })
    //   // } else { //多选一，跳转页面
    //   //   //  TODO

    //   // }
    //   api.showLoading('正在加载中...')
    //   wx.redirectTo({
    //     url: '../prize/prizeSecond/prizeSecond?prizeInfo=' + JSON.stringify(prizeInfo) + '&source=2',
    //   })
    // },
    /**
     * 红包兑奖
     * @param {*} event 
     */
    prizeDraw: function (event) {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        let prizeInfo = event.currentTarget.dataset.prizeinfo;
        let index = event.currentTarget.dataset.index;
        let productType = event.currentTarget.dataset.prizeinfo.productType;
        if (prizeInfo.status == '8') {
            return;
        }
        //防止重复点击或者点击过快
        console.log("点击了");
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 5000); //3秒内不能重复点击
        }
        this.isLoading(true, "正在领取...")
        const that = this;
        log.info('[prizeRecord]--->[receiveWxRedBag]')
        let error_url = productType == 4 ? '../xinyouranPage/prompt/prompt' : productType == 1 ? '../jingdianPage/prompt/prompt' : '../prompt/prompt';

        //兑奖
        netWork.POST('receiveWxRedBag', {
            data: {
                userId: wx.getStorageSync('userId'),
                prizeOrderId: prizeInfo.prizeOrderId,
                prizeId: prizeInfo.prizeId,
                positioningStyle: wx.getStorageSync('positioningStyle') == '' ? '0' : wx.getStorageSync('positioningStyle'),
                positioningType: wx.getStorageSync('positioningType') == '' ? '-1' : wx.getStorageSync('positioningType'),
                latitude: wx.getStorageSync('latitude'),
                longitude: wx.getStorageSync('longitude'),
                speed: wx.getStorageSync('speed'),
                accuracy: wx.getStorageSync('accuracy'),
                source: 1, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
            },
            success: function (res) {
                that.isLoading(false)
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") {
                    wx.showToast({
                        title: '领取成功',
                        icon: 'success'
                    })
                    //更新该prizeOrderid对应的状态
                    that.setData({
                        ['prizeList[' + index + '].status']: 8
                    })
                    that.getCustomerTotalPrizeAmount();
                } else {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                    })
                }

            },
            fail: function () {
                that.isLoading(false)
                wx.redirectTo({
                    url: error_url + '?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
                })
            }
        });


    },
    updateOrder: function (event) {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 3000); //3秒内不能重复点击
        }
        let index = event.currentTarget.dataset.index;
        let prizeInfo = event.currentTarget.dataset.prizeinfo;
        let productType = event.currentTarget.dataset.prizeinfo.productType;
        // if (prizeInfo.materialInfo.receiveExpressOrderCode != null) { //查看物流
        //   this.setData({
        //     isShowModal: true,
        //     ani: 0,
        //     materialInfo: prizeInfo.materialInfo,
        //     productType: prizeInfo.productType
        //   })
        //   this.queryWL();
        // } else {  
        const that = this;

        wx.showModal({
            title: '提示',
            content: '确认收到货了吗？',
            success: function (sm) {
                if (sm.confirm) {
                    that.isLoading(true, "加载中...");
                    let error_url = productType == 4 ? '../xinyouranPage/prompt/prompt' : productType == 1 ? '../jingdianPage/prompt/prompt' : '../prompt/prompt';

                    //兑奖
                    netWork.POST('confirmMatter', {
                        data: {
                            userId: wx.getStorageSync('userId'),
                            prizeOrderId: prizeInfo.prizeOrderId,

                        },
                        success: function (res) {
                            that.isLoading(false)
                            if (res.data.retCode == undefined) {
                                wx.redirectTo({
                                    url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                                })
                            }
                            if (res.data.retCode == "0000") {
                                wx.showToast({
                                    title: '操作成功',
                                    icon: 'success'
                                })
                                //更新该prizeOrderid对应的状态
                                that.setData({
                                    ['prizeList[' + index + '].status']: 14
                                })

                            } else {
                                if(res.data.retCode == "10029"){
                                    wx.redirectTo({
                                        url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                                    }) 
                                }else{
                                    wx.showToast({
                                        title: '操作失败',
                                        icon: 'error'
                                    })
                                }
                            }

                        },
                        fail: function () {
                            that.isLoading(false)
                            wx.showToast({
                                title: '操作失败',
                                icon: 'error'
                            })
                        }
                    });


                } else if (sm.cancel) {
                    return;
                }
            }
        })




    },
    /**
     * 查询看物流
     */
    queryWL: function () {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        api.showLoading('正在查询物流中...')
        const that = this;
        if (that.data.materialInfo.receiveExpressCompany == '业务员派送') {
            that.setData({
                wlInfo: '您的订单由业务员进行派送~'
            })
            return;
        }
        netWork.POST('xhtx/little/searchLogisticsInfo', {
            data: {
                expressOrderCode: that.data.materialInfo.receiveExpressOrderCode,
                expressCompany: encodeURI(that.data.materialInfo.receiveExpressCompany)
            },
            success: function (res) {
                api.cancelLoading();
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == '0000') {
                    if (res.data.data != null && res.data.data != "") {
                        that.setData({
                            wlList: JSON.parse(res.data.data)
                        })
                    }
                } else {
                    if (res.data.retCode == '10045') {
                        that.setData({
                            wlInfo: res.data.retMsg
                        })
                    } else {
                        //查询失败
                        wx.showToast({
                            title: '查询失败，请稍后重试~',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                }
            },
            fail: function (err) {
                api.cancelLoading();
                //查询失败
                wx.showToast({
                    title: '查询失败，请稍后重试~',
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    scanQcord: function () {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        api.scanCode();
    },

    /**
     * 更多活动， 跳转第三方小程序
     */
    showMore: function () {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        this.queryIsFollowGG();
    },
    showGG: function () {
        const that = this;
        if (this.data.integral == 0) {
            wx.showToast({
                title: '您还没有获得积分',
                icon: 'none',
                duration: 2000
            })
            return;
        }
        wx.navigateToMiniProgram({
            appId: api.thirdAppId,
            path: 'pages/home/home',
            envVersion: getApp().globalData.ganguoAppidStyle,
            success(res) {
                console.log('立即领取，跳转甘果')
                //存入缓存，点过立即领取
                wx.setStorageSync('goToganguo', true);
                that.setData({
                    'goToganguo': true
                })
            },
            fail(res) {}

        })
    },
    /**
     *查询是否关注公众号
     */
    queryIsFollowGG: function () {
        this.isLoading(true, "正在查询...");
        const that = this;
        netWork.POST('searchUserInfo', {
            data: {
                userId: wx.getStorageSync('userId')
            },
            success: function (res) {
                that.isLoading(false)
                that.setData({
                    isShowPub: false
                })
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") {
                    if (res.data.data.isFollow == 1) { //关注
                        //跳转中奖记录
                        wx.navigateToMiniProgram({
                            appId: api.thirdAppId,
                            envVersion: getApp().globalData.ganguoAppidStyle
                        })
                    } else { //未关注，引导关注
                        wx.navigateTo({
                            url: '../officialAccount/officialAccount',
                        })
                    }

                } else { //失败，暂时不按未关注处理
                    //跳转中奖记录
                    wx.navigateToMiniProgram({
                        appId: api.thirdAppId,
                        path: 'pages/home/home',
                        envVersion: getApp().globalData.ganguoAppidStyle
                    })
                }
            },
            fail: function () {
                that.setData({
                    isShowPub: false
                })
                that.isLoading(false)
                //跳转中奖记录
                wx.navigateToMiniProgram({
                    appId: api.thirdAppId,
                    path: 'pages/home/home',
                    envVersion: getApp().globalData.ganguoAppidStyle
                })
            }
        });
    },
    //下拉刷新中奖记录
    async onRefresh() {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })

        this.isLoading(true, "正在查询...");
        const that = this;
        that.setData({
            pageNumNew: 1,
            pageNum: 0,
            hidden: false
        });
        //先查询新的订单表
        let prizeList = await this.queryNewPrizeList();
        if (this.data.currentType == 2) {
            this.getCustomerTotalPrizeAmount();
        } else if (this.data.currentType == 3) {
            this.getCustomerTotalPrizeIntegration();
        }
        // console.log(prizeList);
        if (prizeList != null && prizeList != "") {
            that.setData({
                prizeList: prizeList,
                showFlag: prizeList.length,
                zindex: prizeList.length == 0 ? 0 : 9999
            });
            //   if (prizeList.length >= 10) {


            setTimeout(function () {
                that.setData({
                    triggered: false,
                })
                that._freshing = false;
            }, 1000);
            return;
            //   }

        }

        // console.log("[onLoad-pageNum]" + that.data.pageNum);
        // this.setData({
        //   pageNum: 1,
        //   hidden: false
        // })

        // //中奖记录查询
        // netWork.POST('getUserPrizeListByTab', {
        //   data: {
        //     userId: wx.getStorageSync('userId'),
        //     pageNum: 1,
        //     tab:this.data.currentType
        //   },
        //   success: function (res) {
        //     setTimeout(function () {
        //       that.isLoading(false);
        //     }, 1000);


        //     if (res.data.retCode == undefined) {
        //       wx.redirectTo({
        //         url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        //       })
        //     }
        //     if (res.data.retCode == "0000") {
        //       setTimeout(function () {
        //         that.setData({
        //           triggered: false,
        //         })
        //         that._freshing = false;
        //       }, 1000);
        //       // that.setData({
        //       //   prizeList: "",
        //       //   showFlag: 0,
        //       //   zindex: 0
        //       // });
        //       if (res.data.data != null && res.data.data != "") {
        //         let prizeRecordArray = [];
        //         for (var index in res.data.data) {
        //             if(that.data.currentType == 3){
        //                 if (res.data.data[index].prizeType == '3') { //积分奖项特殊处理
        //                     let jf1 = new Object();
        //                     jf1 = JSON.parse(JSON.stringify(res.data.data[index])); //积分
        //                     jf1.prizeName = res.data.data[index].prizeIntegration + '积分';
        //                     prizeRecordArray.push(jf1);
        //                 } else if(res.data.data[index].point != null && res.data.data[index].point != 0) {
        //                     let jf = new Object();
        //                     jf = JSON.parse(JSON.stringify(res.data.data[index])); //积分
        //                     jf.prizeName = res.data.data[index].point + '积分';
        //                     prizeRecordArray.push(jf);
        //                 }
        //             }else{
        //                 prizeRecordArray.push(res.data.data[index]);
        //             }
        //         }
        //         if (prizeList != null && prizeList != "" && that.data.pageNumNew == 1) {
        //           prizeRecordArray = prizeList.concat(prizeRecordArray);
        //         }
        //         that.setData({
        //           prizeList: prizeRecordArray,
        //           showFlag: prizeRecordArray.length,
        //           zindex: prizeRecordArray.length == 0 ? 0 : 9999
        //         });
        //       } else {

        //         if (prizeList != null && prizeList != "") {

        //         } else {
        //           that.setData({
        //             prizeList: "",
        //             showFlag: 0,
        //             zindex: 0
        //           });
        //         }
        //       }
        //     } else {
        //       wx.showToast({
        //         title: '查询失败，请稍后重试~',
        //         icon: 'none',
        //         duration: 2000
        //       })
        //     }

        //   },
        //   fail: function (err) {
        //     that.isLoading(false);
        //     //查询失败
        //     wx.showToast({
        //       title: '查询失败，请稍后重试~',
        //       icon: 'none',
        //       duration: 2000
        //     })

        //   }
        // });

    },
    showPrize() {
        this.setData({
            tabFlag: 'prizeList'
        });
        //清空礼券查询
        //查询
        this.queryPrizeRecord();
    },
    showTicket() {
        console.log('ticket-onclick')
        this.setData({
            tabFlag: 'ticketList'
        });
        //清空中奖记录

        //查询金蝶礼券
        this.queryTicketRecord();
    },
    //生成二维码
    drawImg: function (ticketNo) {
        var imgData = QR.drawImg(ticketNo, {
            typeNumber: 4,
            errorCorrectLevel: 'M',
            size: 500
        })
        return imgData;
    },
    //放大二维码
    bigImg: function (event) {
        let qrcode = event.currentTarget.dataset.qrcode;
        let userule = event.currentTarget.dataset.userule;
        this.setData({
            qrcodeBigURL: qrcode,
            isShowBigQrCode: true,
            useRule: userule
        })
    },
    //关闭放大的二维码
    closeBigQrCode() {
        this.setData({
            isShowBigQrCode: false
        })
    },
    showRuleText: function (event) {
        let ruleText = event.currentTarget.dataset.ruletext;
        console.log(ruleText)
        wx.showToast({
            title: ruleText,
            icon: 'none',
            duration: 2500
        });
    },

    operaBut(e) {
        let item = e.currentTarget.dataset.item; //奖项类型
        let index = e.currentTarget.dataset.index; //奖项类型

        if (item.prizeType == '' || item.prizeType == null || item.prizeType == undefined) { //多选一
            wx.navigateTo({
                url: '../receiptInfo/receiptInfo?source=2&prizeInfo=' + JSON.stringify(item) + '&index=' + index,
            })
        } else if (item.prizeType == '6'||item.prizeType == '20') { //实物奖或奖上奖
            let url = item.productType == 4 ? '../xinyouranPage/' : item.productType == 5 ? '../xinyouranPage/xinyouranHighPage/' : item.productType == 1 ? '../jingdianPage/' : '../';
            console.log(url)
            //跳转到填写礼物页面
            //   wx.navigateTo({
            //     url: url + 'receiptInfo/receiptInfo?source=2&prizeInfo=' + JSON.stringify(item) + '&index=' + index,
            //   })
            this.data.entityIndex = index;
            this.data.entityPrizeId = item.prizeId;
            this.data.entityPrizeOrderId = item.prizeOrderId;
            this.setData({
                entityData: item,
                isShowEntityPopup: true,
                flag: true
            })
            this.receivePrizeHand();
        } else if (item.prizeType == '15') { //优惠券

            //展示核销礼券页面

        }

    },
    queryPrizeRecordInfo(prizeOrderId, index, error_url) {
        //查询礼券的状态
        const that = this;
        return new Promise((resolve, reject) => {
            netWork.POST('xhtx/little/queryPrizeRecord', {
                data: {
                    prizeOrderId: prizeOrderId,
                },
                success: function (res) {
                    that.isLoading(false)
                    if (res.data.retCode == undefined) {
                        wx.redirectTo({
                            url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                        })
                    }
                    if (res.data.retCode == "0000" && res.data.data != null && res.data.data != '') { //成功
                        if (res.data.data.status != null) {
                            //更新状态
                            //更新该prizeOrderid对应的状态
                            that.setData({
                                ['prizeList[' + index + '].status']: res.data.data.status
                            })
                            resolve(res.data.data.status)
                        }
                    } else {
                        //跳转温馨提示页面
                        wx.redirectTo({
                            url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                        })

                    }
                },
                fail: function () {
                    that.isLoading(false);
                    //跳转温馨提示页面
                    wx.redirectTo({
                        url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
            })
        })

    },
    queryJDticketInfo(prizeOrderId, fticketno, index, status, error_url) {
        this.isLoading(true, "正在加载...")
        const that = this;
        netWork.POST('QueryTicketInfo', {
            data: {
                prizeOrderId: prizeOrderId,
                fticketno: fticketno
            },
            success: function (res) {
                that.isLoading(false)
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") { //成功
                    if (res.data.data != null && res.data.data != '') {
                        that.setData({
                            ticket: res.data.data,
                            isShowQRcode: true
                        })
                        that.isLoading(true, "正在加载...")
                        setTimeout(function () {
                            that.setData({
                                qrcodeBigURL: that.drawImg(res.data.data.FTicketNo)
                            })
                            that.isLoading(false)

                        }, 200);
                        if (res.data.data.FTicketStatus == '已过期') {
                            wx.showToast({
                                title: '该优惠券已过期',
                                icon: 'error',
                                duration: 3000
                            })
                            that.updateTicketStatus(fticketno, prizeOrderId, index, res.data.data.FTicketStatus);
                            return;
                        }
                        if (res.data.data.FTicketStatus == '已使用') {
                            wx.showToast({
                                title: '该优惠券已使用',
                                icon: 'error',
                                duration: 3000
                            })
                            //更新列表
                            that.setData({
                                ['prizeList[' + index + '].status']: 11
                            })
                            return;
                        }
                        if (res.data.data.FSource == '001' && status != 13) { //餐饮
                            that.subscribeMessage(prizeOrderId, index, fticketno);
                        }

                    }
                } else {
                    //跳转温馨提示页面
                    wx.redirectTo({
                        url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                    })

                }
            },
            fail: function () {
                that.isLoading(false);
                //跳转温馨提示页面
                wx.redirectTo({
                    url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
        })
    },
    //优惠券立即使用
    async ticketDraw(event) {

        //防止重复点击或者点击过快
        console.log("点击了");
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 2000); //2秒内不能重复点击
        }

        this.isLoading(true, "正在加载...")
        let prizeInfo = event.currentTarget.dataset.prizeinfo;
        let index = event.currentTarget.dataset.index;
        let productType = event.currentTarget.dataset.prizeinfo.productType;
        //判断是否是有赞优惠券
        if (prizeInfo.prizeType == 12) {
            wx.navigateToMiniProgram({
                appId: 'wx785770f82ffbd282',
                path: prizeInfo.prizeValue
            })
            this.isLoading(false)
            return;
        }
        if (prizeInfo.prizeType == 16 || prizeInfo.prizeType == 17) { //16,17
            if (prizeInfo.fticketNo == '' || prizeInfo.fticketNo == null) {
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=优惠券编码为空',
                })
                return;
            }
            // console.log(wx.arrayBufferToBase64(prizeInfo.fticketNo))
            this.subscribeMessageNew(prizeInfo.prizeOrderId, index, prizeInfo.fticketNo, prizeInfo.status, prizeInfo.productType);
            return;
        }
        const that = this;
        let status = await this.queryPrizeRecordInfo(prizeInfo.prizeOrderId, index, productType);
        this.setData({
            ticketName: prizeInfo.prizeName
        })

        if (status == '11' || status == '10') {
            that.isLoading(false)
            setTimeout(function () {
                wx.showToast({
                    title: status == '11' ? '该优惠券已使用' : '该优惠券已过期',
                    icon: 'error',
                    duration: 3000
                })
            }, 1000);
            return;
        }
        let error_url = productType == 4 ? '../xinyouranPage/prompt/prompt' : productType == 1 ? '../jingdianPage/prompt/prompt' : '../prompt/prompt';
        //状态=2,需要同步
        if (status == '2' || prizeInfo.fticketNo == '' || prizeInfo.fticketNo == null) {
            netWork.POST('getTicketNo', {
                data: {
                    prizeOrderId: prizeInfo.prizeOrderId
                },
                success: function (res) {
                    that.isLoading(false);
                    if (res.data.retCode == undefined) {
                        wx.redirectTo({
                            url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                        })
                    }
                    if (res.data.retCode == "0000") {
                        //成功，调用查询礼券详情接口
                        if (res.data.fticketNo == '' || res.data.fticketNo == null) { //礼券为空
                            wx.showToast({
                                title: '优惠券正在发放',
                                icon: 'error'
                            })
                            return;
                        } else { //不为空查询金蝶详情接口

                            that.queryJDticketInfo(prizeInfo.prizeOrderId, res.data.fticketNo, index, status, error_url);
                        }
                    } else {
                        //跳转温馨提示页面
                        wx.redirectTo({
                            url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                        })

                    }
                },
                fail: function () {
                    that.isLoading(false);
                    //跳转温馨提示页面
                    wx.redirectTo({
                        url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
            })
        } else { //不需要同步，
            let ticket = await that.queryJDticketInfo(prizeInfo.prizeOrderId, prizeInfo.fticketNo, index, status, error_url);

        }

    },
    //将base64图片转网络图片
    sendCode(code) {
        let qrcode = code.replace(/\. +/g, '').replace(/[\r\n]/g, '')
        /*code是指图片base64格式数据*/
        //声明文件系统
        const fs = wx.getFileSystemManager();
        //随机定义路径名称
        var times = new Date().getTime();
        var codeImg = wx.env.USER_DATA_PATH + '/' + times + '.png';
        return new Promise((resolve, reject) => {
            //将base64图片写入
            fs.writeFile({
                filePath: codeImg,
                data: qrcode.slice(22),
                encoding: 'base64',
                success: () => {
                    resolve(codeImg)
                }
            });
        })

    },
    async createCanvvasImage() {
        wx.showLoading({
            title: '正在保存...',
        })
        const that = this;
        let ticketNo = "【券号】" + this.data.ticket.FTicketNo; //累计金额
        let time = "【有效期】" + this.data.ticket.FBeginDate + "至" + this.data.ticket.FEndDate; //称号
        let rule1 = "1." + this.data.ticket.FConsumeRule;
        let rule2 = "2." + this.data.ticket.FUseRule
        //背景图
        let headImg = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/successNew/qr_bg_cj.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        //标题
        let titleImgLeft = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/qrcode/ticket_title_l.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        let titleImgRight = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/qrcode/ticket_title_r.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        let kfImg = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/qrcode/kf.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        let qrcodeUrl = await that.sendCode(that.data.qrcodeBigURL);
        //qrcode
        let qrcode = new Promise(function (resolve) {
            wx.getImageInfo({
                src: qrcodeUrl,
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });

        Promise.all([headImg, qrcode, titleImgLeft, titleImgRight, kfImg]).then(function (result) {
            const ctx = wx.createCanvasContext('myCanvas');
            let height = 0; //当前高度
            //背景图
            ctx.drawImage(result[0], 20, 50, 580, 880);
            //临时保存
            ctx.restore();
            //  //二维码
            // ctx.drawImage(result[2], 153, 90, 25, 19);
            ctx.font = 'normal bold 33px Source Han Sans CN';
            ctx.setFillStyle("#B72733"); // 文字颜色
            ctx.setTextAlign("center"); //居中
            ctx.fillText(that.data.ticketName, 310, 120); // 绘制文字
            //二维码
            if (that.data.ticket.FSource == '001') {
                ctx.drawImage(result[1], 190, 160, 250, 250);
            } else {
                ctx.drawImage(result[4], 190, 160, 250, 250);
            }
            //临时保存
            ctx.restore();
            ctx.font = 'normal bold 18px Source Han Sans CN';
            ctx.setFillStyle("#231815"); // 文字颜色
            ctx.setTextAlign("center"); //居中
            ctx.fillText(ticketNo, 300, 470); // 绘制文字
            //临时保存
            ctx.restore();
            ctx.fillText(time, 300, 510); // 绘制文字
            //临时保存
            ctx.restore();

            ctx.font = 'normal bold 18px Source Han Sans CN';
            ctx.setFillStyle("#231815"); // 文字颜色
            ctx.setTextAlign("left");
            ctx.fillText("使用规则:", 90, 570); // 绘制文字
            // //临时保存
            ctx.restore();

            var text = that.data.ticket.FNote;
            // console.log(text)
            var temp = text.split(/[\n,]/g);
            var heights = 610;
            // for(var i =0;i<temp.length;i++){

            // var he = that.drawText(ctx,temp[0],100, heights, heights,432) // 自动
            //heights =he+heights;
            // console.log(temp[i]);
            ctx.restore();
            that.drawText(ctx, temp, 90, heights, heights, 440); // 自动

            ctx.restore();

            // }
            // console.log(he+"he")
            //ctx.draw()
            // ctx.fillText(rule1, 100, 630); // 绘制文字
            //  //临时保存
            //  ctx.restore();
            // ctx.fillText(rule2, 100, 660); // 绘制文字 
            // // //临时保存
            // ctx.restore();
            // ctx.setFillStyle("#bd2f2f"); // 文字颜色
            // ctx.fillText("3.请保存上方二维码，结款时出示给商家！", 100, 690); // 绘制文字
            // //  //临时保存
            //  ctx.restore();
            // ctx.setFillStyle("#231815"); // 文字颜色
            // ctx.fillText("若是实物奖品，请在餐中联系商家兑付，结款时", 100, 720); // 绘制文字
            // ctx.fillText("出示二维码核销该奖品！", 100, 750); // 绘制文字




            let canvasToTempFilePath = "";
            ctx.draw(false, function () {
                // canvas画布转成图片并返回图片地址
                console.log(111)
                wx.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    success: function (res) {
                        // console.log(res.tempFilePath)
                        canvasToTempFilePath = res.tempFilePath
                        that.setData({
                            showShareImg: true
                        })
                        console.log(res.tempFilePath, 'canvasToTempFilePath')
                        console.log("绘制成功");
                        that.saveShareImg(canvasToTempFilePath);
                    },
                    fail: function () {
                        wx.showToast({
                            title: '绘制失败',
                        })
                    },
                    complete: function () {
                        wx.hideLoading()
                        wx.hideToast()
                    }
                })
            })

        })

    },
    drawText: function (ctx, context, leftWidth, initHeight, titleHeight, canvasWidth) {
        //  console.log(str)

        for (var i = 0; i < context.length; i++) {
            var str = context[i];
            var lineWidth = 0;
            var lastSubStrIndex = 0; //每次开始截取的字符串的索引
            ctx.font = 'normal bold 18px Source Han Sans CN';
            ctx.setFillStyle("#231815"); // 文字颜色
            ctx.setTextAlign("left");

            for (let i = 0; i < str.length; i++) {
                lineWidth += ctx.measureText(str[i]).width;
                if (lineWidth > canvasWidth) {

                    ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
                    initHeight += 30; //16为字体的高度
                    lineWidth = 0;
                    lastSubStrIndex = i;
                    titleHeight += 30;
                }
                if (i == str.length - 1) { //绘制剩余部分
                    ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);

                }
            }
            // 标题border-bottom 线距顶部距离
            initHeight = initHeight + 30;
            titleHeight = titleHeight + 10;
        }
        // var res=new Array(ctx,titleHeight);
        return titleHeight;
    },
    // 保存到系统相册
    saveShareImg(canvasToTempFilePath) {
        console.log('canvasToTempFilePath')
        let that = this;
        // 获取用户是否开启用户授权相册
        if (!that.data.openStatus) {
            wx.openSetting({
                success: (result) => {
                    console.log("result.authSettingscope.writePhotosAlbum");
                    console.log(result.authSetting["scope.writePhotosAlbum"] == true);
                    if (result) {
                        if (result.authSetting["scope.writePhotosAlbum"] == true) {
                            that.setData({
                                openStatus: true
                            });
                            wx.saveImageToPhotosAlbum({
                                filePath: canvasToTempFilePath,
                                success: function (data) {
                                    console.log("success")
                                    wx.showToast({
                                        title: '图片保存成功',
                                        icon: 'none',
                                        duration: 1000
                                    })
                                },
                                fail: function (err) {
                                    console.log("fail")
                                    wx.showToast({
                                        title: '保存失败',
                                        icon: 'none'
                                    })
                                }
                            })
                        }
                    }
                },
                fail: () => {
                    wx.getSetting({
                        success(res) {
                            // 如果没有则获取授权
                            if (!res.authSetting['scope.writePhotosAlbum']) {
                                wx.authorize({
                                    scope: 'scope.writePhotosAlbum',
                                    success() {
                                        that.setData({
                                            openStatus: true
                                        })
                                        wx.saveImageToPhotosAlbum({
                                            filePath: canvasToTempFilePath,
                                            success() {
                                                wx.showToast({
                                                    title: '图片保存成功',
                                                    icon: 'none',
                                                    duration: 1000
                                                })
                                            },
                                            fail() {
                                                wx.showToast({
                                                    title: '保存失败',
                                                    icon: 'none'
                                                })
                                            }
                                        })
                                    },
                                    fail() {
                                        // 如果用户拒绝过或没有授权，则再次打开授权窗口
                                        that.setData({
                                            openStatus: false
                                        });
                                        wx.showModal({
                                            title: '用户未授权',
                                            content: '您未开启保存图片到相册的权限，设置开启该权限？',
                                            success: function (sm) {
                                                if (sm.confirm) {
                                                    wx.openSetting()
                                                } else if (sm.cancel) {
                                                    console.log('用户点击取消')
                                                }
                                            }
                                        })

                                    }
                                })
                            } else {
                                // 有则直接保存
                                that.setData({
                                    openStatus: true
                                });
                                wx.saveImageToPhotosAlbum({
                                    filePath: canvasToTempFilePath,
                                    success() {
                                        wx.showToast({
                                            title: '图片保存成功',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                    },
                                    fail() {
                                        wx.showToast({
                                            title: '保存失败',
                                            icon: 'none'
                                        })
                                    }
                                })
                            }
                        },
                        fail(err) {
                            console.log(err)
                        }
                    })
                },
                complete: () => {

                }
            });
        } else {
            wx.getSetting({
                success(res) {
                    // 如果没有则获取授权
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success() {
                                that.setData({
                                    openStatus: true
                                })
                                wx.saveImageToPhotosAlbum({
                                    filePath: canvasToTempFilePath,
                                    success() {
                                        wx.showToast({
                                            title: '图片保存成功',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                    },
                                    fail() {
                                        wx.showToast({
                                            title: '保存失败',
                                            icon: 'none'
                                        })
                                    }
                                })
                            },
                            fail() {
                                // 如果用户拒绝过或没有授权，则再次打开授权窗口
                                that.setData({
                                    openStatus: false
                                });
                                wx.showModal({
                                    title: '用户未授权',
                                    content: '您未开启保存图片到相册的权限，设置开启该权限？',
                                    success: function (sm) {
                                        if (sm.confirm) {
                                            wx.openSetting()
                                        } else if (sm.cancel) {
                                            console.log('用户点击取消')
                                        }
                                    }
                                })
                            }
                        })
                    } else {
                        // 有则直接保存
                        console.log("有则直接保存")
                        that.setData({
                            openStatus: true
                        });
                        wx.saveImageToPhotosAlbum({
                            filePath: canvasToTempFilePath,
                            success() {
                                wx.showToast({
                                    title: '图片保存成功',
                                    icon: 'none',
                                    duration: 1000
                                })
                            },
                            fail() {
                                wx.showToast({
                                    title: '保存失败',
                                    icon: 'none'
                                })
                            }
                        })
                    }
                },
                fail(err) {
                    console.log(err)
                }
            })
        }
    },
    async closeTicket() {
        // api.showLoading('正在加载中...');
        //查询优惠券信息
        // let ticket = await that.queryJDticketInfo();
        // console.log(ticket)
        this.setData({
            isShowQRcode: false,
            ticket: "",
            qrcodeBigURL: ""
        })

        // onRefresh()
    },
    isLoading(isLoading, loadingText) {
        this.setData({
            isLoading: isLoading,
            loadingText: loadingText
        })
    },
    gotoTicket() {
        wx.navigateTo({
            url: '/pages/h5Test/htTest',
        })
    },
    updateTicketStatus(tickNo, billNo, index) {
        const that = this;
        netWork.POST('/ticketConfirm', {
            data: {
                ticketNo: tickNo,
                billNo: billNo,
                type: 3 //过期
            },
            success: function (res) {
                if (res.data.retCode == undefined) {}
                if (res.data.retCode == "0000") {
                    //更新列表
                    that.setData({
                        ['prizeList[' + index + '].status']: 10
                    })
                } else {

                }
            },
            fail: function () {

            }
        })
    },
    //查询总共打开多少瓶
    getOpendCount() {
        const that = this;
        //兑奖
        netWork.POST('getOpendCount', {
            data: {
                userId: wx.getStorageSync('userId')
            },
            success: function (res) {
                if (res.data.retCode == "0000") {
                    console.log(res.data);
                    var opendCount = res.data.data.opendCount;
                    if (typeof opendCount != 'undefined') {
                        that.setData({
                            opendCount: opendCount
                        })
                    }
                }

            },
            fail: function (res) {

            }
        });
    },
    // 订阅信息的下发授权
    subscribeMessageNew: function (prizeOrderId, index, fticketNo, status, productType) {
        let that = this;
	    let error_url = productType == 4 ? '../xinyouranPage/prompt/prompt' : productType == 1 ? '../jingdianPage/prompt/prompt' : productType == 2 ? '../prompt/prompt' : productType == 3 ? '../ruiPage/prompt/prompt' : '../xinyouranPage/xinyouranHighPage/prompt/prompt';
        try {
            if (status != 10 && status != 11 && status != 13) {
                //请求立即使用接口
                netWork.POST('ticketUsed', {
                    data: {
                        userId: wx.getStorageSync('userId'),
                        prizeOrderId: prizeOrderId,
                        ticketNo: Base64.encode(fticketNo).replace(/=/g, "")
                    },
                    success: function (res) {
                        if(res.data.retCode == "10029"){
                            wx.redirectTo({
                                url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                            }) 
                        }

                    },
                    fail: function (res) {
                        that.isLoading(false)
                    }
                });
            }
            that.isLoading(false)
            if (status == 13 || productType == 3) {
                wx.navigateTo({
                    url: '../commonPage/ticket/ticket?fticketNo=' + encodeURIComponent(fticketNo)
                })
                return;
            }
            wx.getSetting({
                withSubscriptions: true, //这句怎么无效
                success(e) {
                    try {
                        var mainSwitch = e.subscriptionsSetting.mainSwitch;
                        if (mainSwitch) {
                            //true，总开关订阅消息
                            console.log(e.subscriptionsSetting.itemSettings);
                            if (typeof e.subscriptionsSetting.itemSettings != 'undefined') { //
                                var size = 0;
                                var key;
                                var obj = e.subscriptionsSetting.itemSettings;
                                for (key in obj) { //obj中存在几个关键字
                                    if (obj.hasOwnProperty(key))
                                        size++;
                                }
                                if (size != 2) {
                                    that.setData({
                                        isSubMsg: true
                                    })
                                }
                            } else { //没有该节点弹出
                                that.setData({
                                    isSubMsg: true
                                })
                            }
                        }
                    } catch (e1) {

                    }

                }
            })
            wx.requestSubscribeMessage({
                tmplIds: ['KyJMnBXyKJ1nrCQiMfRDCZnT-JLSMVo1cz98jC85cKg', 'mLYNe8uqrdlB28ymi8g70TMXtaZ-Apc2ZIf_6gbudco', 'WNN9vqU-qSPjlpN8kj8J5OMIbqXKbSkqGN3YvAu_w0A'],
                success(res) {
                    var subscriptionData = [];
                    for (let key in res) {
                        if (key !== "errMsg" && key !== "errorCode") {
                            let obj = {
                                template_id: key,
                                status: res[key]
                            };
                        }
                        console.log(res)
                        log.info(res);
                        that.setData({
                            isSubMsg: false
                        })
                    }
                    console.log(fticketNo)
                    wx.navigateTo({
                        url: '../commonPage/ticket/ticket?fticketNo=' + encodeURIComponent(fticketNo),
                    })

                },
                fail(res) {
                    console.log(res);
                    that.setData({
                        isSubMsg: false
                    })
                    wx.navigateTo({
                        url: '../commonPage/ticket/ticket?fticketNo=' + encodeURIComponent(fticketNo),
                    })
                }
            })
        } catch (err) { // 当前微信版本不支持订阅信息
            console.error("subscribeMessage-err", err);
        }
    },
    // 订阅信息的下发授权
    subscribeMessage: function (prizeOrderId, index, ticketNo) {
        let that = this;
        try {
            //请求立即使用接口
            netWork.POST('ticketUsed', {
                data: {
                    userId: wx.getStorageSync('userId'),
                    prizeOrderId: prizeOrderId,
                    ticketNo: Base64.encode(ticketNo).replace(/=/g, "")
                },
                success: function (res) {
                    if (res.data.retCode == "0000") {
                        //更新状态为13-核销中
                        that.setData({
                            ['prizeList[' + index + '].status']: 13
                        })
                    }

                },
                fail: function (res) {

                }
            });
            wx.getSetting({
                withSubscriptions: true,
                success(e) {
                    try {
                        var mainSwitch = e.subscriptionsSetting.mainSwitch;
                        if (mainSwitch) {
                            //true，总开关订阅消息
                            console.log(e.subscriptionsSetting.itemSettings);
                            if (typeof e.subscriptionsSetting.itemSettings != 'undefined') { //
                                var size = 0;
                                var key;
                                var obj = e.subscriptionsSetting.itemSettings;
                                for (key in obj) { //obj中存在几个关键字
                                    if (obj.hasOwnProperty(key))
                                        size++;
                                }
                                if (size != 2) {
                                    that.setData({
                                        isSubMsg: true
                                    })
                                }
                            } else { //没有该节点弹出
                                that.setData({
                                    isSubMsg: true
                                })
                            }
                        }
                    } catch (e1) {

                    }

                }
            })
            wx.requestSubscribeMessage({
                tmplIds: ['KyJMnBXyKJ1nrCQiMfRDCZnT-JLSMVo1cz98jC85cKg', 'mLYNe8uqrdlB28ymi8g70TMXtaZ-Apc2ZIf_6gbudco', 'WNN9vqU-qSPjlpN8kj8J5OMIbqXKbSkqGN3YvAu_w0A'],
                success(res) {
                    var subscriptionData = [];
                    for (let key in res) {
                        if (key !== "errMsg" && key !== "errorCode") {
                            let obj = {
                                template_id: key,
                                status: res[key]
                            };
                        }
                        console.log(res)
                        log.info(res);
                        that.setData({
                            isSubMsg: false
                        })
                    }


                },
                fail(res) {
                    console.log(res);
                    that.setData({
                        isSubMsg: false
                    })
                }
            })
        } catch (err) { // 当前微信版本不支持订阅信息
            console.error("subscribeMessage-err", err);
        }
    },
    closeSub() {
        this.setData({
            isSubMsg: false
        })
    },
    returnIndex() {
        const that = this;
        wx.removeStorageSync('isMemberDay');
        wx.removeStorageSync('qrCode');
        let productType = wx.getStorageSync('productType');
        let url = productType == 4 ? '../xinyouranPage/index/index' : productType == 1 ? '../jingdianPage/index/index' : productType == 3 ? '../ruiPage/index/index' : productType == 2 ? '../index/index' : productType == 5 ? '../xinyouranPage/xinyouranHighPage/index/index' : '../commonPage/index/index';
        console.log('productType:' + productType);
        if (this.data.sendType == "sendEntity") {
            wx.redirectTo({
                url: '../scan/scan'
            })
            return;
        }
        if (productType == 1) {
            that.isLoading(true, "加载中...");
            netWork.POST('/getLastScanProductType', {
                data: {
                    userId: wx.getStorageSync('userId')
                },
                success: function (res) {
                    that.isLoading(false);
                    if (res.data.retCode == "0000") {
                        if (res.data.data) {
                            let isMemberDay = res.data.data.isMemberDay;
                            console.log('isMemberDay:' + isMemberDay)
                            if (isMemberDay) {
                                wx.setStorageSync('isMemberDay', isMemberDay);
                                wx.redirectTo({
                                    url: '../jingdianPage/memberDayIndex/memberDayIndex',
                                })
                                return;
                            } else {
                                wx.redirectTo({
                                    url: url,
                                })
                            }
                        }

                    } else {
                        wx.redirectTo({
                            url: url,
                        })
                    }

                },
                fail: function () {
                    that.isLoading(false);
                    wx.redirectTo({
                        url: url,
                    })
                }
            })
        } else {
            wx.redirectTo({
                url: url,
            })
        }


    },
    onShow() {
        // const that = this;
        // if (that.data.height != 527) {
        //   return;
        // }
        // let query = wx.createSelectorQuery();
        // query.select('.bnt-rm').boundingClientRect(rect => {
        //   let clientWidth = rect.width;
        //   let ratio = 750 / clientWidth;
        //   let clientBottom = rect.bottom;
        //   console.log('rect.bottom' + rect.bottom);
        //   let clientHeight = wx.getSystemInfoSync().windowHeight * ratio;

        //   console.log('屏幕高度' + clientHeight);
        //   console.log('按钮高度' + clientBottom * ratio);
        //   let bottom = clientHeight - (clientBottom * ratio) - 30;
        //   that.setData({
        //     height: bottom >= 100 ? 527 + bottom : 527,
        //   })
        //   console.log("距离底部的高度：" + bottom)
        // }).exec();
        // 根据文档，先创建一个SelectorQuery对象实例
        let query = wx.createSelectorQuery().in(this);
        // 然后逐个取出navbar和header的节点信息
        // 选择器的语法与jQuery语法相同
        query.select('#viewFrame').boundingClientRect();
        query.select('.menu').boundingClientRect();
        query.select('.typeTab').boundingClientRect();
        // 执行上面所指定的请求，结果会按照顺序存放于一个数组中，在callback的第一个参数中返回
        query.exec((res) => {
            let viewFrameHeight = res[0].height;
            let menuHeight = res[1].height;
            let tabHeight = res[2].height;
            // 然后就是做个减法
            let scrollViewHeight = viewFrameHeight - menuHeight - tabHeight;
            // 算出来之后存到data对象里面
            this.setData({
                couponScrollViewHeight: scrollViewHeight
            });
        });
        try {
            if (wx.onNeedPrivacyAuthorization) {
                wx.onNeedPrivacyAuthorization(resolve => {
                    this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                    this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                    this.resolvePrivacyAuthorization = resolve
                })
            }
        } catch (error) {
            console.info(error)
        }
    },
    //获取地理位置组参加密跳转博饼H5
    async enterPancake(e) {
        let index = e.currentTarget.dataset.index;
        let url = await bobing.getBobingKey(this, netWork, this.data.prizeList[index].prizeValue);
        if (url) {
            let replace = url.replace(/\+/g, '%2B');
            getApp().globalData.bobingPathAndParams = replace;
            wx.navigateTo({
                url: '../jingdianPage/bobingWebview/bobingWebview'
            })
        }
    },
    /**
     * 打开设置
     */
    openSetting() {
        this.setData({
            isShowModalAuth: false
        })
        api.putOpenSetting();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function (e) {
        var that = this;
        //请求数据
        model.updateAreaData(that, 0, e);
    },
    //关闭实物弹窗
    async closeEntityPopup(e) {
        let item = e.currentTarget.dataset.item;
        let productType = item.productType;
        this.setData({
            isShowEntityPopup: false
        })
        //   if(productType == 1 || productType == 2 || productType == 3){
        let flag = await isShowReminderOfExpired(item.prizeOrderId);
        if (!flag) {
            return;
        }
        try {
            wx.getSetting({
                withSubscriptions: true, //这句怎么无效
                success(e) {
                    try {
                        var mainSwitch = e.subscriptionsSetting.mainSwitch;
                        if (mainSwitch) {
                            //true，总开关订阅消息
                            console.log(e.subscriptionsSetting.itemSettings);
                            if (typeof e.subscriptionsSetting.itemSettings != 'undefined') { //
                                var size = 0;
                                var key;
                                var obj = e.subscriptionsSetting.itemSettings;
                                for (key in obj) { //obj中存在几个关键字
                                    if (obj.hasOwnProperty(key))
                                        size++;
                                }
                                if (size != 2) {
                                    // that.setData({
                                    //     isSubMsg: true
                                    // })
                                }
                            } else { //没有该节点弹出
                                // that.setData({
                                //     isSubMsg: true
                                // })
                            }
                        }
                    } catch (e1) {

                    }

                }
            })
            wx.requestSubscribeMessage({
                tmplIds: ['LSxspuNVTeYOVS4ezti_HTaoH8cCw3iaX9CEik1iIKQ'],
                success(res) {
                    var subscriptionData = [];
                    for (let key in res) {
                        if (key !== "errMsg" && key !== "errorCode") {
                            let obj = {
                                template_id: key,
                                status: res[key]
                            };
                        }
                        console.log(res)
                        log.info(res);
                    }
                    if (res['LSxspuNVTeYOVS4ezti_HTaoH8cCw3iaX9CEik1iIKQ'] != "reject") {
                        let list = wx.getStorageSync('reminderOfExpiredList') || [];
                        list.push(item.prizeOrderId);
                        wx.setStorageSync('reminderOfExpiredList', list);
                    }
                },
                fail(res) {
                    console.log(res);
                }
            })
        } catch (err) { // 当前微信版本不支持订阅信息
            console.error("subscribeMessage-err", err);
        }
        //   }
    },
    //实物弹窗判断姓名输入框是否有值显示隐藏小手
    userName(e) {
        this.data.materialInfo.receiveName = e.detail.value;
        this.setData({
            materialInfo: this.data.materialInfo
        })
        this.receivePrizeHand();
    },
    userPhone(e) {
        this.data.materialInfo.receivePhone = e.detail.value;
        this.setData({
            materialInfo: this.data.materialInfo
        })
        this.receivePrizeHand();
    },
    userDetailAddress(e) {
        this.data.materialInfo.receiveAddress = e.detail.value;
        this.setData({
            materialInfo: this.data.materialInfo
        })
        this.receivePrizeHand();
    },
    //表单提交按钮,校验
    formSubmit: function (e) {
        //防止重复点击或者点击过快
        console.log("点击了");
        if (!isClickReceivePrizes) {
            console.log("重复返回~");
            return;
        }
        if (isClickReceivePrizes) {
            isClickReceivePrizes = false;
            //定时器
            setTimeout(function () {
                isClickReceivePrizes = true;
            }, 5000); //3秒内不能重复点击
        }
        let userName = e.detail.value.userName;
        let phone = e.detail.value.phone;
        let detailAddress = e.detail.value.detailAddress;
        if (userName.trim() == "") {
            wx.showToast({
                title: '请输入收件人姓名',
                icon: 'none'
            })
            return;
        }
        if (userName.length > 20) {
            wx.showToast({
                title: '收件人姓名不能超过20个文字',
                icon: 'none'
            })
            return;
        }
        if (phone.trim() == "") {
            wx.showToast({
                title: '请输入手机号码',
                icon: 'none'
            })
            return;
        }

        let a = /^1\d{10}$/;
        if (!a.test(phone)) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none'
            })
            return;
        }
        if (this.data.address == '请选择地区') {
            wx.showToast({
                title: '请选择地区',
                icon: 'none'
            })
            return;
        }
        if (detailAddress.trim() == "") {
            wx.showToast({
                title: '请输入详细地址',
                icon: 'none'
            })
            return;
        }
        if (detailAddress.length > 60) {
            wx.showToast({
                title: '详细地址不能超过60个文字',
                icon: 'none'
            })
            return;
        }
        this.setData({
            formValue: e.detail.value,
            addressMsg: detailAddress
        })
        let materialInfo = {};
        materialInfo['receiveProvinceId'] = addressInfo.receiveProvinceId;
        materialInfo['receiveCityId'] = addressInfo.receiveCityId;
        materialInfo['receivceDistrictId'] = addressInfo.receivceDistrictId;
        materialInfo['receiveProvinceName'] = addressInfo.receiveProvinceName;
        materialInfo['receiveCityName'] = addressInfo.receiveCityName;
        materialInfo['receiveDistrictName'] = addressInfo.receiveDistrictName;
        materialInfo['receiveName'] = userName;
        materialInfo['receivePhone'] = phone;
        materialInfo['receiveAddress'] = detailAddress;
        wx.setStorageSync('materialInfo', materialInfo)
        this.revicePrize();
    },
    /**
     * 点击领取,进行实物奖兑奖
     */
    revicePrize: function () {
        this.isLoading(true, "正在提交...");
        const that = this;
        //兑奖
        netWork.POST('receiveMatter', {
            data: {
                userId: wx.getStorageSync('userId'),
                prizeOrderId: that.data.entityPrizeOrderId,
                prizeId: that.data.entityPrizeId,
                positioningStyle: wx.getStorageSync('positioningStyle'),
                positioningType: wx.getStorageSync('positioningType'),
                latitude: wx.getStorageSync('latitude'),
                longitude: wx.getStorageSync('longitude'),
                speed: wx.getStorageSync('speed'),
                accuracy: wx.getStorageSync('accuracy'),
                receiveName: that.data.formValue.userName, //收货人
                receivePhone: that.data.formValue.phone, //收货电话
                receiveProvinceId: addressInfo.receiveProvinceId, //省
                receiveCityId: addressInfo.receiveCityId, //市
                receivceDistrictId: addressInfo.receivceDistrictId, //区
                receiveProvinceName: addressInfo.receiveProvinceName,
                receiveCityName: addressInfo.receiveCityName,
                receiveDistrictName: addressInfo.receiveDistrictName,
                receiveAddress: that.data.formValue.detailAddress, //地址
                source: 2, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
            },
            success: function (res) {
                that.isLoading(false);
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") {
                    that.data.prizeList[that.data.entityIndex].status = '8'; //更新为领取成功
                    that.setData({
                        prizeList: that.data.prizeList,
                        isShowEntityPopup: false,
                        isShowEntityTips: true
                    })
                } else if (res.data.retCode == "10052") {
                    setTimeout(function () {
                        wx.showToast({
                            title: '收货信息不支持表情等特殊字符，请修改后再提交哦~',
                            icon: 'none',
                            duration: 3000
                        })
                    }, 100)
                } else {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                    })
                }
            },
            fail: function (res) {
                that.isLoading(false);
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
                })
            }
        });
    },
    //点击选择城市按钮显示picker-view
    translate: function (e) {
        console.log('点击了')
        model.animationEvents(this, 0, true, 400);
    },
    //城市隐藏picker-view
    hiddenFloatView: function (e) {
        model.animationEvents(this, 200, false, 400);
        if (e.target.dataset.id == '555') {
            return;
        }
        if (this.data.address == '请选择省/市/区' || JSON.stringify(addressInfo) == '{}' || (this.data.item.value[0] == 0 && this.data.item.value[1] == 0 && this.data.item.value[2] == 0)) {
            addressInfo = {
                "receiveProvinceId": '110000',
                "receiveCityId": '110100',
                "receivceDistrictId": '110101',
                "receiveProvinceName": '北京市',
                "receiveCityName": '北京市',
                "receiveDistrictName": '东城区'
            };

        }
        this.setData({
            address: addressInfo.receiveProvinceName + ' ' + addressInfo.receiveCityName + ' ' + addressInfo.receiveDistrictName,
        })
        this.receivePrizeHand();
    },
    //城市滑动事件
    bindChange: function (e) {
        model.updateAreaData(this, 1, e);
        item = this.data.item;
        addressInfo = {
            "receiveProvinceId": item.provinces[item.value[0]].id,
            "receiveCityId": item.citys[item.value[1]].id,
            "receivceDistrictId": item.countys[item.value[2]].id,
            "receiveProvinceName": item.provinces[item.value[0]].name,
            "receiveCityName": item.citys[item.value[1]].name,
            "receiveDistrictName": item.countys[item.value[2]].name
        };
    },
    //关闭实物领取成功提示
    closeEntityTips() {
        this.setData({
            isShowEntityTips: false
        })
    },
    //菜单选择
    async selectMenu(e) {
        let index = e.currentTarget.dataset.index;
        this._freshing = false;
        this.setData({
            currentType: index,
            pageNumNew: 1,
            pageNum: 0,
            prizeList: [],
            currentTypeTabIndex: 1
        })
        if (this.data.commonHeight == 200) {
            await this.setScrollViewHeight();
        }
        this.queryPrizeRecord();
        if (index == 2) {
            this.getCustomerTotalPrizeAmount();
        } else if (index == 3) {
            this.getCustomerTotalPrizeIntegration();
        }
    },
    setScrollViewHeight() {
        // 根据文档，先创建一个SelectorQuery对象实例
        let query = wx.createSelectorQuery().in(this);
        // 选择器的语法与jQuery语法相同
        query.select('#viewFrame').boundingClientRect();
        query.select('.menu').boundingClientRect();
        if (this.data.currentType == 2) {
            query.select('.topHeight').boundingClientRect();
        } else {
            query.select('.jftopHeight').boundingClientRect();
        }
        // 执行上面所指定的请求，结果会按照顺序存放于一个数组中，在callback的第一个参数中返回
        query.exec((res) => {
            let viewFrameHeight = res[0].height;
            let menuHeight = res[1].height;
            let topHeight = res[2].height;
            // 然后就是做个减法
            let scrollViewHeight = viewFrameHeight - menuHeight - topHeight;
            this.setData({
                commonHeight: scrollViewHeight
            })
        })
    },
    //根据用户一年之内成功领取的红包总值
    getCustomerTotalPrizeAmount() {
        let that = this;
        netWork.POST('getCustomerTotalPrizeAmount', {
            data: {
                userId: wx.getStorageSync('userId')
            },
            success: function (res) {
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") {
                    that.setData({
                        redEnvelopNum: res.data.totalPrizeAmount
                    })
                } else {
                    wx.showToast({
                        title: '查询失败，请稍后重试~',
                        icon: 'none',
                        duration: 2000
                    })
                }
            },
            fail: function (err) {
                that.isLoading(false);
                //查询失败
                wx.showToast({
                    title: '查询失败，请稍后重试~',
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    //根据用户一年之内成功领取的积分总值
    getCustomerTotalPrizeIntegration() {
        let that = this;
        netWork.POST('getCustomerTotalPrizeIntegration', {
            data: {
                userId: wx.getStorageSync('userId')
            },
            success: function (res) {
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") {
                    that.setData({
                        integral: res.data.totalPrizeIntegration
                    })
                } else {
                    wx.showToast({
                        title: '查询失败，请稍后重试~',
                        icon: 'none',
                        duration: 2000
                    })
                }
            },
            fail: function (err) {
                that.isLoading(false);
                //查询失败
                wx.showToast({
                    title: '查询失败，请稍后重试~',
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    receivePrizeHand() {
        if (!this.data.materialInfo.receiveName || !this.data.materialInfo.receivePhone || !this.data.materialInfo.receiveAddress) {
            this.setData({
                handFlag: false
            })
            return;
        }
        let userName = this.data.materialInfo.receiveName;
        let phone = this.data.materialInfo.receivePhone;
        let detailAddress = this.data.materialInfo.receiveAddress;
        if (userName.trim() == "") {
            this.setData({
                handFlag: false
            })
            return;
        }
        if (userName.length > 20) {
            this.setData({
                handFlag: false
            })
            return;
        }
        if (phone.trim() == "") {
            this.setData({
                handFlag: false
            })
            return;
        }

        let a = /^1\d{10}$/;
        if (!a.test(phone)) {
            this.setData({
                handFlag: false
            })
            return;
        }
        if (this.data.address == '请选择地区') {
            this.setData({
                handFlag: false
            })
            return;
        }
        if (detailAddress.trim() == "") {
            this.setData({
                handFlag: false
            })
            return;
        }
        if (detailAddress.length > 60) {
            this.setData({
                handFlag: false
            })
            return;
        }
        this.setData({
            handFlag: true
        })
    },
    //消息推送进入页面打开实物弹窗
    openEntityPopup(prizeOrderId) {
        let that = this;
        netWork.POST('xhtx/little/queryPrizeRecord', {
            data: {
                prizeOrderId: prizeOrderId,
            },
            success: function (res) {
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt' + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000" && res.data.data != null && res.data.data != '') { //成功
                    if (res.data.data.status == 10 || res.data.data.status == 14 || res.data.data.status == 8) {
                        let text = res.data.data.status == 10 ? "奖品已过期" : "奖品已领取";
                        wx.setStorageSync('showToastText', text)
                        that.returnIndex();
                    } else if (res.data.data.status == 1) {
                        that.data.entityPrizeId = res.data.data.prizeId;
                        that.data.entityPrizeOrderId = res.data.data.prizeOrderId;
                        that.setData({
                            entityData: res.data.data,
                            isShowEntityPopup: true,
                            flag: true
                        })
                        that.receivePrizeHand();
                    }
                } else {
                    //跳转温馨提示页面
                    wx.redirectTo({
                        url: '../prompt/prompt' + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                    })
                }
            },
            fail: function () {
                that.isLoading(false);
                //跳转温馨提示页面
                wx.redirectTo({
                    url: '../prompt/prompt' + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
        })
    },
    //获取世界杯竞猜信息
    async getPickInfo(e) {
        let item = e.currentTarget.dataset.item; //奖项类型
        if (item.status == 10) {
            return;
        }
        this.setData({
            showFootball: true
        })
        this.selectComponent('#football').setData({
            footballPrizeInfo: item
        })
        this.selectComponent('#football').getData();
    },
    //修改世界杯竞猜奖励状态
    setPrizeStatus(e) {
        let prizeOrderId = e.detail.prizeOrderId;
        let index = 0;
        let status = e.detail.status;
        for (let i = 0; i < this.data.prizeList.length; i++) {
            if (this.data.prizeList[i].prizeOrderId == prizeOrderId) {
                index = i;
                break;
            }
        }
        this.data.prizeList[index].status = status;
        if (this.data.prizeList[index].worldcupInfo == null) {
            this.data.prizeList[index].worldcupInfo = {
                status: 0
            };
        }
        this.setData({
            prizeList: this.data.prizeList,
            showFootball: false
        })
        // this.setHandFlag();
    },
    //劵、将下的tab
    selectTypeTab(e) {
        let index = e.currentTarget.dataset.index;
        this._freshing = false;
        this.setData({
            pageNumNew: 1,
            pageNum: 0,
            prizeList: [],
            currentTypeTabIndex: index
        })
        this.queryPrizeRecord()
    },
    //权益卡跳转详情页
    async benefitCardDetails(e) {
        let item = e.currentTarget.dataset.prizeinfo;
        let index = e.currentTarget.dataset.index;
        let flag = await isShowReminderOfExpired(item.prizeOrderId);
        if(flag){
            requestSubscribeMessage(item.prizeOrderId);
        }
        wx.navigateTo({
            url: '/pages/commonPage/benefitCardDetails/benefitCardDetails?prizeOrderId='+item.prizeOrderId+'&entryMode=prizeRecord'+'&entryModeDataIndex='+index
        })
    },
})